package com.bawei.home

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.entity.SimpleVideoEntity
import com.bawei.common.mvi.BaseMviFragment
import com.bawei.home.adapter.HomeVideoListAdapter
import com.bawei.home.databinding.FragmentHomeListBinding
import com.bawei.home.intent.HomeViewIntent
import com.bawei.home.state.HomeUiState
import com.bawei.home.vm.HomeViewModel
import com.blankj.utilcode.util.CrashUtils.OnCrashListener
import com.bumptech.glide.Glide
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch


@AndroidEntryPoint
class HomeListFragment: BaseMviFragment<FragmentHomeListBinding>() {

    private val mViewModel: HomeViewModel by activityViewModels()
    private var pageIndex = 1
    private var pageSize = 10
    private lateinit var mVideoListAdapter: HomeVideoListAdapter
    private var simpleVideoList = mutableListOf<SimpleVideoEntity>()
    private var typeId = 0
    private var channelId = ""

    companion object{
        @JvmStatic
        fun newInstance(typeId: Int, channelId: String) =
            HomeListFragment().apply {
                arguments = Bundle().apply {
                    putInt("typeId", typeId)
                    putString("channelId", channelId)
                }
            }
    }


    override fun getLayoutId(): Int = R.layout.fragment_home_list

    override fun initViews() {
        //获取参数
        arguments?.let {
            typeId = it.getInt("typeId")
            channelId = it.getString("channelId").toString()
        }

        //列表下拉刷新事件
        mDataBinding.refreshLayout.setOnRefreshListener {
            pageIndex = 1
            refreshOrMoreList()
        }

        //RecyclerView优化设置
        var cachePool = RecyclerView.RecycledViewPool().apply {
            setMaxRecycledViews(0, 5) //适用于多布局， viewType必须在适配器中ItemType一致
        }
        mDataBinding.rvHomeList.apply {
            setHasFixedSize(true) //Item是否属于固定大小，减少组件测量时间
            setItemViewCacheSize(20) //Item缓存大小
            setRecycledViewPool(cachePool) //设置缓存池
        }

        //页面滚动时暂停图片加载
        mDataBinding.rvHomeList.addOnScrollListener(object : OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(this@HomeListFragment).resumeRequests() //恢复图片加载
                } else {
                    Glide.with(this@HomeListFragment).pauseRequests() //暂停图片加载
                }
            }
        })

        //关闭不需要的动画
        (mDataBinding.rvHomeList.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

        mVideoListAdapter = HomeVideoListAdapter(simpleVideoList)
        mVideoListAdapter.apply {
            preloadEndCount = 4
            preloadData = {
                pageIndex += 1
                refreshOrMoreList()
            }
        }

        mDataBinding.rvHomeList.run {
            layoutManager =  LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
            swapAdapter(mVideoListAdapter, true) //开启屏幕外缓存
        }

        //设置点击事件
        mVideoListAdapter.setOnItemClickListener(object : HomeVideoListAdapter.OnItemClickListener{
            override fun onItemClick(v: View, position: Int) {
                when(v.id){
                    R.id.iv_video_play -> {
                        ARouter.getInstance().build(RoutePath.PATH_PLAY_PAGE)
                            .withInt("typeId", typeId)
                            .withString("channelId", channelId)
                            .withSerializable("videoEntity", simpleVideoList[position])
                            .navigation()
                    }
                    R.id.iv_commend -> {

                    }

                    R.id.iv_more -> {

                    }
                }
            }
        })

    }

    private fun refreshOrMoreList(){
        lifecycleScope.launch {
            if (typeId == -1){
                mViewModel.channel.send(HomeViewIntent.LoadRecommendSimpleVideoList(pageIndex, pageSize))
            }else{
                mViewModel.channel.send(HomeViewIntent.LoadSimpleVideoListById(channelId, pageIndex, pageSize))
            }
        }
    }

    fun lazyLoadData(){
        //清理不是同类数据
        if (simpleVideoList.size > 0 && simpleVideoList[0].channelid != channelId){
            simpleVideoList.clear()
            mVideoListAdapter.notifyDataSetChanged()
        }
        //不是同类数据，需要重新加载
        refreshOrMoreList()
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is HomeUiState.LoadSimpleVideoSuccess -> updatePageData(it.list)
                is HomeUiState.LoadSimpleVideoFail -> {
                    //页码重置到加载之前页码
                    if (pageIndex > 1){
                        pageIndex -= 1
                    } else {
                      simpleVideoList.clear()
                      mVideoListAdapter.notifyDataSetChanged()
                    }
                }
                else -> {}
            }
        }
    }

    private fun updatePageData(list: List<SimpleVideoEntity>){
        if (pageIndex == 1){
            mDataBinding.refreshLayout.finishRefresh()
            simpleVideoList.clear()
        }
        simpleVideoList.addAll(list)
        mVideoListAdapter.notifyDataSetChanged()

    }


}